import * as server_ui from "@minecraft/server-ui";
import * as server from "@minecraft/server";
import * as data_prompt from "../data/prompt";
import * as data_block from "../data/block";
import * as data_story from "../data/story";
import * as derived_tools from "../system/derived_tools";
import * as native_tools from "../system/native_tools";
import * as achieve_plan from "../system/achieve_plan";
import * as query_intel from "../system/query_intel";
import * as math_tools from "../system/math_tools";
export function FaerieHealingTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 100))
                return;
            const options = {
                excludeTypes: ["minecraft:item", "minecraft:xp_orb"],
                excludeFamilies: ["monster"],
                location: player.location,
                maxDistance: 8
            };
            player.dimension.getEntities(options).forEach(entity => entity.addEffect("regeneration", 300, { amplifier: 4, showParticles: false }));
            const molang = new server.MolangVariableMap();
            molang.setFloat('variable.size', 8);
            molang.setFloat('variable.direction', 3);
            player.playSound('item.book.page_turn');
            native_tools.TrySpawnParticle(player.dimension, 'scripts:path_spiral', player.location, molang);
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
            native_tools.SetDurability(player, item, container, player.selectedSlotIndex, 1);
        }
    };
}
;
export function ForestryGuidelinesTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 100))
                return;
            const start = math_tools.Vector.add(player.location, { x: -5, y: -1, z: -5 });
            const done = math_tools.Vector.add(player.location, { x: 5, y: 15, z: 5 });
            const moveEvent = (args) => {
                const TestSort = () => {
                    const getBlock = args.dimension.getBlock(args.location);
                    if (getBlock)
                        return data_block.is_trees.has(getBlock.typeId);
                    else
                        return false;
                };
                if (TestSort())
                    args.dimension.runCommand(`fill ${args.location.x} ${args.location.y} ${args.location.z} ${args.location.x} ${args.location.y} ${args.location.z} air [] destroy`);
                return true;
            };
            player.playSound('item.book.page_turn');
            achieve_plan.PathExecute.CreateForCube('林业指南-范围扫描', {
                particles: ['constant:track_rune_green'],
                location_group: [],
                dimension: player.dimension,
                cooldown: 1,
                speed: 1,
                on_move: moveEvent
            }, start, done, 0.25);
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
            native_tools.SetDurability(player, item, container, player.selectedSlotIndex, 1);
        }
    };
}
;
export function MineralDictionaryTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 100))
                return;
            const start = math_tools.Vector.add(player.location, { x: -5, y: -9, z: -5 });
            const done = math_tools.Vector.add(player.location, { x: 5, y: 9, z: 5 });
            const moveEvent = (args) => {
                const TestSort = () => {
                    const getBlock = args.dimension.getBlock(args.location);
                    if (getBlock)
                        return data_block.is_mineral.has(getBlock.typeId);
                    else
                        return false;
                };
                if (TestSort()) {
                    args.dimension.runCommand(`fill ${args.location.x} ${args.location.y} ${args.location.z} ${args.location.x} ${args.location.y} ${args.location.z} air [] destroy`);
                    const options = {
                        location: args.location,
                        type: "minecraft:item",
                        maxDistance: 4
                    };
                    args.dimension.getEntities(options).forEach(entity => entity.teleport(player.getHeadLocation(), { dimension: player.dimension }));
                }
                return true;
            };
            player.playSound('item.book.page_turn');
            achieve_plan.PathExecute.CreateForCube('矿物辞典-范围扫描', {
                particles: ['constant:track_color_indigo'],
                location_group: [],
                dimension: player.dimension,
                cooldown: 1,
                speed: 1,
                on_move: moveEvent
            }, start, done, 0.25);
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
            native_tools.SetDurability(player, item, container, player.selectedSlotIndex, 1);
        }
    };
}
;
export function SpaceTransitionTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 100))
                return;
            const RoadSign = new Map();
            player.getDynamicPropertyIds().filter(id => id.startsWith('road_sign:')).forEach(id => native_tools.CompileSign(player, id, RoadSign));
            player.playSound('item.book.page_turn');
            if (player.isSneaking) {
                const anchor = math_tools.QueryEntityFoothold(player, 10, 512);
                if (math_tools.Vector.distance(anchor, player.location) > 3)
                    player.teleport(anchor);
                server.system.runTimeout(() => player.playSound("conduit.attack"), 5);
            }
            else
                BasePresets().show(player).then(option => {
                    if (option.canceled)
                        return;
                    switch (option.selection) {
                        case 0:
                            RelativePresets().show(player).then(option => RenRelative(player, option));
                            break;
                        case 1:
                            RandomPresets().show(player).then(option => RenRandom(player, option));
                            break;
                        case 2:
                            SignPresets(RoadSign).show(player).then(option => RenRoadSign(player, option, RoadSign));
                            break;
                    }
                });
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
            native_tools.SetDurability(player, item, container, player.selectedSlotIndex, 1);
        }
    };
}
;
function BasePresets() {
    const title = {
        text: "§9《§5 空间宝典 §9》§r"
    };
    const option = [
        { text: '<§4§o§l 相对传送 §r>' },
        { text: '<§5§o§l 随机传送 §r>' },
        { text: '<§9§o§l 诸界道标 §r>' }
    ];
    const display = new server_ui.ActionFormData()
        .title(title)
        .button(option[0], "textures/物品贴图/魔法书籍/空间宝典")
        .button(option[1], "textures/物品贴图/魔法书籍/魔导手册")
        .button(option[2], "textures/物品贴图/魔法书籍/空间宝典");
    return display;
}
;
function RelativePresets() {
    const title = {
        text: "§9《§5 空间宝典 §9》§r"
    };
    const option = [
        { text: '§3相对§a X轴坐标§r' },
        { text: '§3相对§a Y轴坐标§r' },
        { text: '§3相对§a Z轴坐标§r' }
    ];
    const display = new server_ui.ModalFormData()
        .title(title)
        .slider(option[0], -64, 64, 1, 0)
        .slider(option[1], -64, 64, 1, 0)
        .slider(option[2], -64, 64, 1, 0);
    return display;
}
;
function RandomPresets() {
    const title = {
        text: "§9《§5 空间宝典 §9》§r"
    };
    const option = [
        { text: '§3偏移§a X轴基准§r' },
        { text: '§3偏移§a Y轴基准§r' },
        { text: '§3偏移§a Z轴基准§r' },
        { text: '§3设置§a 极限范围§r' }
    ];
    const display = new server_ui.ModalFormData()
        .title(title)
        .slider(option[0], -16, 16, 1, 0)
        .slider(option[1], -16, 16, 1, 0)
        .slider(option[2], -16, 16, 1, 0)
        .slider(option[3], 16, 255, 1, 16);
    return display;
}
;
function SignPresets(input) {
    const name = Array.from(input.keys()).map(id => `§n§o§l§${Math.floor(Math.random() * 6)}` + id.split(':')[1]);
    const title = {
        text: "§9《§5 空间宝典 §9》§r"
    };
    const option = [
        { text: '<§2§o§l 创建道标 §r>' },
        { text: '<§5§o§l 道标传送 §r>' },
        { text: '<§4§o§l 移除道标 §r>' }
    ];
    const text = [
        { text: '<§2§o§l 识别标签 §r> -> §9重命名' },
        { text: '§c请输入 诸界道标 识别标签§r' },
        { text: '§c是否启用<§2§o§l 雾海裂隙 §r>§r' }
    ];
    const display = new server_ui.ModalFormData()
        .title(title)
        .dropdown('', name.length !== 0 ? name : ["§4暂无 §9道标信息§r"], name.length > 1 ? name.length - 1 : 0)
        .dropdown('', option, name.length !== 0 ? 1 : 0)
        .textField(text[0], text[1], math_tools.NumberID().toString())
        .toggle(text[2], false);
    return display;
}
;
function RenRelative(player, option) {
    if (option.canceled)
        return;
    const location = math_tools.Vector.add(player.location, {
        x: parseInt(option.formValues[0]),
        y: parseInt(option.formValues[1]),
        z: parseInt(option.formValues[2]),
    });
    player.teleport(location);
    server.system.runTimeout(() => player.playSound("mob.endermen.portal"), 2);
}
;
function RenRandom(player, option) {
    if (option.canceled)
        return;
    const location = math_tools.Vector.add(player.location, {
        x: parseInt(option.formValues[0]),
        y: parseInt(option.formValues[1]),
        z: parseInt(option.formValues[2]),
    });
    const anchor = math_tools.QueryFoothold({ location: location, dimension: player.dimension }, parseInt(option.formValues[3]), -60, 300);
    player.teleport(anchor);
    server.system.runTimeout(() => player.playSound("mob.endermen.portal"), 5);
}
;
function RenRoadSign(player, option, input) {
    if (!option.formValues)
        return;
    const value = Array.from(input.values());
    const name = Array.from(input.keys());
    const pointLocation = player.location;
    const pointDimension = player.dimension;
    const forms = option.formValues;
    const selfAnchor = JSON.stringify({ location: player.location, dimension: player.dimension.id });
    switch (forms[1]) {
        case 0:
            player.setDynamicProperty('road_sign:' + forms[2], selfAnchor);
            break;
        case 1:
            if (forms[3])
                server.system.runTimeout(() => MistySeaFissure(player, pointLocation, pointDimension), 5);
            player.teleport(value[forms[0]].location, { dimension: value[forms[0]].dimension });
            server.system.runTimeout(() => player.playSound("mob.endermen.portal"), 5);
            break;
        case 2:
            player.setDynamicProperty(name[forms[0]]);
            break;
    }
    ;
}
;
function MistySeaFissure(player, location, dimension) {
    const origin = math_tools.Vector.add(player.location, math_tools.Vector.CONSTANT_UP);
    server.system.runTimeout(() => {
        achieve_plan.MistySeaFissure.Create('', 30, {
            location_group: [
                origin,
                location
            ],
            dimension_group: [
                player.dimension,
                dimension
            ]
        });
        player.playSound("ambient.weather.thunder", { location: player.location, volume: 10 });
        native_tools.TrySpawnParticle(player.dimension, 'constant:fireworks_fireball_amber_color', origin);
        native_tools.TrySpawnParticle(player.dimension, 'constant:smoke_rune_white', origin);
    }, 100);
}
;
export function FaerieContractTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 100))
                return;
            const options = {
                excludeTypes: ["minecraft:item", "minecraft:xp_orb"],
                excludeFamilies: ["monster"]
            };
            const Distance = (entity) => Math.floor(math_tools.Vector.distance(player.location, entity.location));
            const queue = native_tools.EntitysSort(player.dimension, options, (a, b) => Distance(a) - Distance(b), entity => entity.getComponent('minecraft:tameable'));
            const title = {
                text: "§9《§5 精灵结契 §9》§r"
            };
            const display = new server_ui.ActionFormData().title(title);
            const Intel = (entity) => {
                return {
                    rawtext: [
                        { text: '§l' },
                        native_tools.EntityTranslate(entity),
                        { text: `\n§9距离: §5${Distance(entity)}` }
                    ]
                };
            };
            if (queue.length >= 1)
                queue.forEach(entity => display.button(Intel(entity), "textures/物品贴图/魔法书籍/精灵结契"));
            else
                display.button('§4§l周围不存在 §c<§9 可以§6<§u 契约 §6>§9的实体 §c>§r', "textures/物品贴图/魔法书籍/战术规划");
            player.playSound('item.book.page_turn');
            display.show(player).then(option => {
                if (option.selection == undefined || queue.length == 0)
                    return;
                queue[option.selection].getComponent('minecraft:tameable')?.tame(player);
                server.system.runTimeout(() => container?.setItem(player.selectedSlotIndex), 5);
                server.system.runTimeout(() => player.playSound('conduit.deactivate'), 1);
            });
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
        }
    };
}
;
export function IntroductionMagicTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            if (!player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 20))
                return;
            derived_tools.DisplayChunkBoundary(player);
            const chunk = math_tools.Vector.chunkLocation(player.location);
            const notify = data_story.message_notify.get(math_tools.Vector.toString(chunk));
            if (!notify || notify.size < 1)
                return player.playSound('respawn_anchor.deplete');
            const keys = Array.from(notify.keys());
            const value = Array.from(notify.values());
            const title = { text: "§9《§5 魔导绪论 §9》§r" };
            const rawMessage = { rawtext: [] };
            const display = new server_ui.ActionFormData().title(title).button('§u§l关闭§r').button('§4§l清除§r');
            keys.forEach((key, index) => {
                rawMessage.rawtext?.push({ text: `『 ${key} 』\n` }, value[index], { text: '\n\n=====================\n' });
            });
            display.body(rawMessage);
            display.show(player).then(option => {
                if (option.canceled || option.selection == undefined)
                    return;
                if (option.selection == 1)
                    notify.clear();
            });
            player.playSound('beacon.activate');
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
        }
    };
}
;
export function SourceEnergyTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            if (!player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 20))
                return;
            const keys = Array.from(data_prompt.entry.keys());
            const value = Array.from(data_prompt.entry.values()).map(item => item.map(info => info.refer));
            const title = {
                text: "§9《§5 源能秘典 §9》§r"
            };
            const display = new server_ui.ActionFormData().title(title);
            keys.forEach(key => display.button('§l§u' + key, "textures/物品贴图/魔法书籍/源能秘典"));
            display.show(player).then(option => {
                if (option.canceled || option.selection == undefined)
                    return;
                new server_ui.ActionFormData()
                    .title('§l§u§o' + keys[option.selection])
                    .body({ rawtext: value[option.selection] })
                    .button('§4§l关闭§r')
                    .show(player);
            });
            player.playSound('item.book.page_turn');
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
        }
    };
}
;
export function MagicHandbook(player, item, block) {
    player.playSound('item.book.page_turn');
    if (block)
        query_intel.GameHelp(player, block);
    item.getComponent('minecraft:cooldown')?.startCooldown(player);
}
;
